(:
  A procedure to select the contents of the "tokentextboard" interventions 
  regarding who owns the lock. limited to 170 events for stack overflow reasons
:)
declare boundary-space strip;
import module namespace
    jj = "http://kumquat.emse.fr/utilitaires"
    at "jjutils.xq" ;
declare variable $alltokenevents := 
	for $event in doc($arguments[1])/trace/event[./tokentextboard] 
	let $type := string($event/tokentextboard/Token/@type)
	where ($type eq "RELEASE_LOCK" or $type eq "LOCK_ASKED_FOR" or $type eq "FORCE_RELEASE")
	return
		$event;
declare variable $tokenevents := $alltokenevents[position() < 170];
declare function local:remove ($list as xs:string*, $s as xs:string) as item()* 
		{
			for $elem in $list where (xs:string($elem) ne $s) 
			return $elem
		};
declare function local:token-holder-list (
										$i as xs:integer,
										$fifo as xs:string*, 
										$token-holder as xs:string,
										$token-holders as xs:string*) as xs:string* 
		{
			let $j := $i+1
			let $event := $tokenevents[$i]
			let $type := string($event//Token/@type)
			let $user := string($event/@user)
			let $content := $event//Token/text()
			let $nextfifo := if ($type eq "RELEASE_LOCK")
								then local:remove($fifo,$user)
								else if ($type eq "LOCK_ASKED_FOR")
								then ($fifo,$user)
								else local:remove($fifo,string($content))
			let $nexttoken-holder := if (fn:empty($nextfifo)) then " " else $nextfifo[1]			
			let $nexttoken-holders := if ($nexttoken-holder eq $token-holder)
										then ($token-holders,"")
										else ($token-holders,$nexttoken-holder)					
			return
				if ($j gt fn:count($tokenevents))
				then $nexttoken-holders
				else local:token-holder-list($j,$nextfifo,$nexttoken-holder,$nexttoken-holders) 
		};
 
<display>{
let $t := $arguments[1]
let $holders := local:token-holder-list(1,()," ",())
for $e at $p in $tokenevents
let $holder := $holders[$p]
where $holder ne ""
return
<item>{
    <info name="type">textboard</info> ,
    <info name="time">{ $e/time }</info>,
    <info name="src-anchor">{
      <anchor>{
        <doc>{ $t }</doc>,
        <path>{jj:build-Path($e)}</path>
      }</anchor>
    }</info>,
    <info name="user">{string($e/@user)}</info>,
    <info name="room">{string($e/@room)}</info>,
    <info name="content">{
       <text color="darkred">{if ($holder ne " ") then string($holder) else "nobody"} has the token</text> 
    }</info>
  }</item>
}</display>
